from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect, render


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        # 排除那些不需要登录就能访问的页面
        # request.path_info 获取当前用户请求的URL /login/
        if request.path_info in ["/login/", "/image/code/", "/logout/", ]:
            return

        # 读取当前访问的用户的session信息，如果能读到，说明已登陆过，就可以继续向后走。
        info_dict = request.session.get("info")
        # print(info_dict["level"])
        # print(request.path_info)
        if not info_dict:
            # 没有登录过，重新回到登录页面
            return redirect('/login/')
        elif info_dict["level"] == 0 and request.path_info not in [ # 用户可以访问的界面
            "/record/list/",
            "/record/add/day/",
            "/record/download/excel/",
            "/chart/list/7/",
            "/chart/bar/7/",
            "/chart/pie/7/",
            "/chart/line/7/",
            "/chart/list/30/",
            "/chart/bar/30/",
            "/chart/pie/30/",
            "/chart/line/30/",
            "/info/list/",
        ]:
            return render(request, 'error.html')
        else:
            return
